package com.scorpio.security.interceptor;

import com.scorpio.appuser.domain.UserEntity;
import com.scorpio.appuser.service.UserServer;
import com.scorpio.common.constant.AppHttpStatus;
import com.scorpio.common.constant.Constants;
import com.scorpio.common.exception.CustomException;
import com.scorpio.security.annotation.PersonalLogin;
import com.scorpio.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 个人用户登录拦截器
 */
@Component
public class PersonalAuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserServer personalService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        PersonalLogin annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(PersonalLogin.class);
        } else {
            return true;
        }
        if (annotation == null) {
            return true;
        }
        String token = tokenService.getToken(request);
        if (StringUtils.isEmpty(token)) {
            throw new CustomException("请登录后操作", AppHttpStatus.UNAUTHORIZED);
        }
        UserEntity userEntity = personalService.getLoginUser(token);
        if (userEntity == null) {
            throw new CustomException("登录信息过期", AppHttpStatus.FORBIDDEN);
        }
        request.setAttribute(Constants.LOGIN_USER_KEY, userEntity);
        return super.preHandle(request, response, handler);
    }
}
